<?php

namespace app\xwam\model;

/**
 * ProductPromotionItems 模型类
 *
 * @since 1.0 <2017-3-23> SoChishun <14507247@qq.com> Added.
 */
class ProductPromotionItemsModel extends AppbaseModel {

    protected $table = 't_porg_product_promotion_items';

    /**
     * 获取id_text列表
     * @param type $site_id
     * @param type $key_is_id
     * @return type
     * @since 1.0 2016-5-30 SoChishun Added.
     */
    public function getIdTextList($site_id, $key_is_id = false) {
        $list = array();
        if ($key_is_id) {
            $list = $this->where(array('site_id' => $site_id))->cache('productpromotion_idtext_kvlist_' . $site_id, 10)->getField('id, title as text');
        } else {
            $list = $this->where(array('site_id' => $site_id))->cache('productpromotion_idtext_list_' . $site_id, 10)->field('id, title as text')->select();
        }
        return $list;
    }

    function savePromotion() {
        $rules = array(
            array('title', 'require', '标题无效!', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
            array('user_name', 'require', '用户无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('site_id', 'number', 'SiteID无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
        );
        if (!$this->validate($rules)->create()) {
            return $this->returnMsg(false, $this->getError());
        }
        if (empty($this->id)) {
            unset($this->data['id']);
            $result = $this->add();
        } else {
            $result = $this->save();
        }
        return $this->returnMsg($result);
    }

    function changeStatus($id, $status) {
        $result = $this->where(array('id' => $id))->setField(array('status' => $status));
        return $this->returnMsg($result);
    }

    function changeSort($id, $sort) {
        $result = $this->where(array('id' => $id))->setField(array('sort' => $sort));
        return $this->returnMsg($result);
    }

    function deletePromotion($id) {
        $result = $this->delete($id);
        return $this->returnMsg($result);
    }

    /**
     * 获取商品列表
     * @param type $code
     * @param type $field
     * @return type
     * @since 1.0 2016-8-30 SoChishun Added.
     */
    function get_product_list($code, $options) {
        $pids = $this->where(array('code' => $code))->getField('product_ids');
        if (!$pids) {
            return false;
        }
        if (empty($options['field'])) {
            $options['field'] = 'id, title, picture_url, market_price, price';
        }
        $options['table'] = 't_porg_product_goods';
        $options['where'] = array('id' => array('in', $pids));
        return $this->select($options);
    }

}
